// MongoChatService.java
package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.mongodb.ChatMessage;
import cn.edu.lingnan.mongodb.ChatSession;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import org.bson.types.ObjectId;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MongoChatService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public JSONArray getAllSessionsByUserId(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "updatedAt"));
        List<ChatSession> sessions = mongoTemplate.find(query, ChatSession.class);
        return new JSONArray(Collections.singletonList(sessions));
    }

    public ChatSession createSession(Long userId, String firstMessage) {
        ChatSession session = new ChatSession();
        session.setUserId(userId);
        session.setSessionTitle(firstMessage.substring(0, Math.min(firstMessage.length(), 10)));
        session.setCreatedAt(new Date());
        session.setUpdatedAt(new Date());
        return mongoTemplate.insert(session); // sessionId由MongoDB自动生成
    }

    public void validateSessionOwnership(String sessionId, Long userId) {
        //ObjectId objectId = new ObjectId(sessionId);
        ChatSession session = mongoTemplate.findOne(
                Query.query(Criteria.where("id").is(sessionId)),
                ChatSession.class
        );
        log.info("[permission test]"+session.getUserId().toString());
        if (session == null || !session.getUserId().equals(userId)) {
            throw new SecurityException("会话不存在或权限不足");
        }
    }

    public JSONArray getHistoryMessages(String sessionId, Long userId) {
        //validateSessionOwnership(sessionId, userId);
        log.info('1'+sessionId);
        Query query = new Query(Criteria.where("sessionId").is(sessionId))
                .with(Sort.by(Sort.Direction.ASC, "createdAt"));
        List<ChatMessage> messages = mongoTemplate.find(query, ChatMessage.class);
        log.info('2'+messages.toString());
        return new JSONArray(Collections.singletonList(messages));
    }

    public void saveUserMessage(String sessionId, String content) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setRole("user");
        chatMessage.setContent(content);
        chatMessage.setSequenceNumber(getNextSequenceNumber(sessionId));
        chatMessage.setCreatedAt(new Date());
        mongoTemplate.insert(chatMessage);
    }

    public void saveAiMessage(String sessionId, String content) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setRole("assistant");
        chatMessage.setContent(content);
        chatMessage.setSequenceNumber(getNextSequenceNumber(sessionId));
        chatMessage.setCreatedAt(new Date());
        mongoTemplate.insert(chatMessage);
    }

    private int getNextSequenceNumber(String sessionId) {
        Query query = new Query(Criteria.where("sessionId").is(sessionId));
        query.with(Sort.by(Sort.Direction.DESC, "sequenceNumber"));
        query.limit(1);

        ChatMessage lastMessage = mongoTemplate.findOne(query, ChatMessage.class);
        return lastMessage == null ? 1 : lastMessage.getSequenceNumber() + 1;
    }

    public void updateSessionTime(String sessionId) {
        mongoTemplate.updateFirst(
                Query.query(Criteria.where("_id").is(sessionId)),
                new Update().set("updatedAt", new Date()),
                ChatSession.class
        );
    }

    // MongoChatService.java 中添加以下方法

    /**
     * 删除单个会话及其关联消息
     */
    public void deleteSession(String sessionId, Long userId) {
        // 验证会话所有权
        //validateSessionOwnership(sessionId, userId);

        // 删除会话
        mongoTemplate.remove(
                Query.query(Criteria.where("_id").is(sessionId)),
                ChatSession.class
        );

        // 删除关联的所有消息
        mongoTemplate.remove(
                Query.query(Criteria.where("sessionId").is(sessionId)),
                ChatMessage.class
        );
    }

    /**
     * 批量删除会话及其关联消息
     */
    public void batchDeleteSessions(List<String> sessionIds, Long userId) {
        // 验证每个会话的所有权
//        for (String sessionId : sessionIds) {
//            validateSessionOwnership(sessionId, userId);
//        }

        // 批量删除会话
        mongoTemplate.remove(
                Query.query(Criteria.where("_id").in(sessionIds)),
                ChatSession.class
        );

        // 批量删除关联的所有消息
        mongoTemplate.remove(
                Query.query(Criteria.where("sessionId").in(sessionIds)),
                ChatMessage.class
        );
    }

}